Skip to main content
Version: 2.14.4 - 2.14.0

Integrated Libraries

This category specifies protocols imported from the outside libraries.

warning

WORK IN PROGRESS: This manual is currently being updated and may not contain all the necessary information.

Introduction

The following libraries were implemented:

note

Beware, that linked documentation is not always complete and the article tries to link these for cross-reference purposes

note

Beware, that while the aforementioned libraries are implemented, not all the functions may be enabled. Consult the rest of the article for further details.

eLua Bit Module library

Since Lua doesn't have (yet) built-in capabilities for bit operations, the bit module was added to eLua to fill this gap. It is based on the bitlib library written by Reuben Thomas (slightly adapted to eLua) and provides basic bit operations (like setting and clearing bits) and bitwise operations.

Overview

FunctionShort DescriptionNote
bit.bnotbitwise negation
bit.bandbitwise AND
bit.borbitwise OR
bit.bxorexclusive bitwise OR
bit.lshiftlogical bitwise left shift
bit.rshiftlogical bitwise right shift
bit.arshiftarithmetic bitwise right shift
bit.bitgenerate a bit number
bit.setset bits in a number
bit.clearset bits in a number
bit.issetcheck if the value in bits is set
bit.isclearcheck if the value in bits is clear

bit.bnot(value)

Bitwise negation, equivalent to ~value in C.


bit.band(value1, value2, ...)

Returns bitwise AND of all of its arguments. Note that more than two arguments are allowed.


bit.bor(value1, value2, ...)

Returns bitwise OR of all of its arguments. Note that more than two arguments are allowed.


bit.bxor(value1, value2, ...)

Returns exclusive bitwise OR of all of its arguments. Note that more than two arguments are allowed.


bit.lshift(value, shiftPosition)

Returns the bitwise logical left-shift of its first argument by the number of bits given by the second argument.

Logical shifts treat the first argument as an unsigned number and shift in 0-bits.


bit.rshift(value, shiftPosition)

Returns the bitwise logical right-shift of its first argument by the number of bits given by the second argument.

Logical shifts treat the first argument as an unsigned number and shift in 0-bits.


bit.arshift(value, shiftPosition)

Returns the bitwise arithmetic right-shift of its first argument by the number of bits given by the second argument.

Arithmetic right-shift treats the most-significant bit as a sign bit and replicates it.


bit.bit(position)

Generate a number with a 1 bit (used for mask generation), Equivalent to 1 << position in C.


bit.set(value, position1, position2, ...)

Sets bits in a number.


bit.clear(value, position1, position2, ...)

Clears bits in a number.


bit.isset(value, position)

Tests if a given bit is set - basically opposite of bit.isclear().


bit.isclear(value, position)

Tests if a given bit is cleared - basically opposite of bit.isset().


Lua BitOp

Lua BitOp is a C extension module for Lua 5.1/5.2 which adds bitwise operations on numbers.

Overview

FunctionShort DescriptionNote
bit.tohexhex string conversion
bit.rolbitwise left rotation
bit.rorbitwise right rotation

bit.tohex(value, absoluteValue)

Converts its first argument to a hex string.

The number of hex digits is given by the absolute value of the optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used.

The default is to generate 8 lowercase hex digits.


bit.rol(value1, value2)

Returns the bitwise left rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side.

Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).


bit.ror(value1, value2)

Returns the bitwise right rotation of its first argument by the number of bits given by the second argument. Bits shifted out on one side are shifted back in on the other side.

Only the lower 5 bits of the rotate count are used (reduces to the range [0..31]).


eLua Pack Module library

This Lua module contains two methods pack.pack for serialization and pack.unpack for deserialization. Both of them use a "format" string to describe how to pack/unpack the data. The format string contains one or more data specifiers, each data specifier is applied to a single variable that must be packed/unpacked. The data specifier has the following general format:

[endianness]<format specifier>[count]

endianness can be chosen based on following table:

Endiannes symbolMeaning
'<'little endian
'>'big endian
'='native endian (the platform's endian order, default).

Format can be choosen based on following table:

Format specifierCorresponding variable type
'z'zero-terminated string
'p'string preceded by length byte
'P'string preceded by length word
'a'string preceded by length size_t
'A'string
'f'float
'd'double
'n'Lua number
'c'char
'b'byte = unsigned char
'h'short
'H'unsigned short
'i'int
'I'unsigned int
'l'long
'L'unsigned long

Deserialization

Deserialization can be used for example when you receive data over LoRaWAN/NB and need to separate each byte to proccess the value. This function will extract each byte into separate variable.

nextpos, val1, val2, ..., valn = pack.unpack( string, format, [ init ] )
--string - the string to unpack.
--format - format specifier.
--init - (optional) marks where in string the unpacking should start (1 if not specified).

Lets say, we sent a simple command to the device using 1B, for example 0x01 (send ID) or 0x02 (send current data). We throw away first byte, as it contains value for nextpos and load cmd variable with received command.

received = "02" 
--received data as string
toSend = 0
-- Example of an ID
-- instead you can use function to read ID
id = 0x92198717

-- received one byte
_, cmd = pack.unpack(received, "b", 1)
--first byte thrown away, loaded cmd

api.dumpArray(cmd)
--result 02
--show received cmd in console

Serialization

Serialization can be used to send data over LoRa or NB. It will pack multiple variables into single string.

packed = pack.pack( format, val1, val2, ..., valn )
--format - format specifier.
--val1 - first variable to pack.
--val2 - second variable to pack.
--valn - nth variable to pack.

Example of packing six 1B variables into one string in little endian.

-- Example of data 
t_hour = 9
t_min = 30
d1 = 0xA1
d2 = 0xC2
d3 = 0xE3
checksum = 0x22

print("Send current data")
toSend = pack.pack("<b6", t_hour, t_min, d1, d2, d3, checksum)
-- at this point, toSend = 0x091EA1C2E322 with format of little endiean byte

api.nbSend(ip, port, toSend, 1000, proto)
api.dumpArray(toSend)

Example of packing mutltiple different data formats into single string

t_hour = 9
t_min = 30
str = "test"
size_t = string.len (str)
d1 = 0xD1 --integer value
d2 = 0x4143eb85 --12.32 in IEEE-754 Floating Point format with big endian
d3 = 0xE3 --integer value
checksum = 22

print("Send current data")
toSend = pack.pack("<b3 <A1 <b1 >f <b1 <b1", t_hour, t_min, size_t, str, d1, d2, d3, checksum)
-- at this point, toSend = \x09\x1E\x04\x74\x65\x73\x74\xD1\xB8\x1E\x45\x41\xE3\x16 with format of little endiean byte

api.dumpArray(toSend)
print(toSend)

Unpacking previous data with python script

from construct import *

input_data = Struct(
"t_hour" / Int8ul,
"t_min" / Int8ul,
"str" / PascalString(VarInt,"utf8"),
"d1" / Int8ul,
"d2" / Float32b,
"d3" / Int8ul,
"checksum" / Int8ul,
)

result = input_data.parse(b'\x09\x1E\x04\x74\x65\x73\x74\xD1\xB8\x1E\x45\x41\xE3\x16')

>>> result.t_hour
9
>>> result.t_min
30
>>> result.str
'test'
>>> result.d1
209
>>> result.d2
12.319999694824219
>>> result.d3
227
>>> result.checksum
22

Lua Math Library

Library used mainly for pre-determined mathematical functions.

info

Note, that the converters use only integers for mathematical functions, therefore only some of them are available to use.

Overview

FunctionShort DescriptionNote
math.absabsolute value
math.hugereturns maximum numerical value
math.maxpick the highest value
math.minpick the lowest value
math.powpower
math.randomrandom number
math.randomrandom number with bottom ceiling
math.randomseedseed randomization
math.sqrtsquare root

math.abs(integer)

The abs() function in Lua’s math library returns the absolute value of a given number.


math.huge

This creates a maximum possible number, in our case, a maximum value of an integer.


math.max(integer1, integer2, ...)

The max() function picks a highest value from the individual values specified in the arguments.


math.min(integer1, integer2, ...)

The min() function picks a lowest value from the individual values specified in the arguments.


math.pow(intToBeRaised, intRaiseWith)

A number(x) in the first argument raised to the power of a number(y) in the second argument (you can also use x ^ y).


math.random(intMaxValue)

Creates a random value with the argument being the maximum value and starting at 1 by default.

note

Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible.

This api.randInt() is not available on NB-IoT devices, so there you would use this one.


math.random(intMinValue, intMaxValue)

Creates a random value, with the arguments being the minimum and maximum value.

note

Note, that api.randInt() is commonly used and ideal to generate random numbers, but this function is also possible.

This api.randInt() is not available on NB-IoT devices, so there you would use this one.


math.randomseed(integer)

Seeds the random number generator with an integer.


math.sqrt(integer)

Calculates the square root of a number, but converted to an integer.


Lua Debug Library

debug.debug()

Enters an interactive mode with the user, creating a breakpoint running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues its execution.

Note that commands for debug.debug are not lexically nested within any function and so have no direct access to local variables.

Example

	debug.debug()
at("ON_TAU_EVENT",1)
print("on_tau_event turned on")
debug.debug()
at("SLEEP_MONITOR",1)
print("sleep monitor turned on")
note

Note, that using this function in the interactive mode causes the device to reboot.

debug.gethook([thread])

Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook function).


debug.getinfo([thread], function, [what])

Returns a table with information about a function. You can give the function directly, or you can give a number as the value of function, which means the function running at level function of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo; and so on. If function is a number larger than the number of active functions, then getinfo returns nil. The returned table can contain all the fields returned by lua_getinfo, with the string what describing which fields to fill in. The default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds a field named func with the function itself. If present, the option 'L' adds a field named activelines with the table of valid lines. For instance, the expression debug.getinfo(1,"n").name returns a table with a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print function.


debug.getlocal([thread], level, local)

This function returns the name and the value of the local variable with index local of the function at level level of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.) Variable names starting with '(' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).


debug.getregistry()

Returns the registry table.


debug.getmetatable(object)

Returns the metatable of the given object or nil if it does not have a metatable.


debug.getupvalue(func, up)

This function returns the name and the value of the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index.


debug.sethook([thread], hook, mask, [count])

Sets the given function as a hook. The string mask and the number count describe when the hook will be called. The string mask may have the following characters, with the given meaning:

"c" the hook is called every time Lua calls a function; "r" the hook is called every time Lua returns from a function; "l" the hook is called every time Lua enters a new line of code.

With a count different from zero, the hook is called after every count instructions. When called without arguments, debug.sethook turns off the hook. When the hook is called, its first parameter is a string describing the event that has triggered its call: "call", "return" (or "tail return", when simulating a return from a tail call), "line", and "count". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more information about the running function (level 0 is the getinfo function, and level 1 is the hook function), unless the event is "tail return". In this case, Lua is only simulating the return, and a call to getinfo will return invalid data.


debug.setlocal([thread], level, local, value)

This function assigns the value value to the local variable with index local of the function at level level of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.


debug.setmetatable(object, table)

Sets the metatable for the given object to the given table (which can be nil).


debug.setupvalue(func, up, value)

This function assigns the value value to the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.


debug.traceback([thread], [message], [level])

Returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback).


Lua String Library

This library enables additional possibilities for working with text - strings and characters.

Overview

FunctionShort DescriptionNote
string.bytecharacter numerical code
string.bytecharacter numerical code
string.findstring pattern search
string.formatcreating formatted strings
string.gmatch
string.gsubreplacing substring with a substring
string.lenmeasuring string length
string.lowerlowercase conversion
string.upperuppercase conversion
string.match
string.reprepeating a string
string.reversereversing a string
string.subextracting a substring
string.index

string.byte(stringOrChar)

Returns the numerical code of the first character of the string.


string.byte(string, intPosition)

Returns the numerical code of the character in the string on a specific position.



string.find(string, strImSearchingFor, intSearchIndex, boolPattern)

Searches for a specific string or character in a string and returns its position if found.


string.format(strFormat, value1, value2, ...)

The .format() function is used to create formatted strings by replacing placeholders with specified values.


string.gmatch(string, integer)

Returns an iterator function for returning the next capture from a pattern over a string. If there is no capture, the whole match is produced.


string.gsub(strToModify, strToBeReplaced, strThatIsReplacing)

Modifies a part of string by replacing it with another string.


string.len(stringToMeasure)

Returns a length of the string in an integer representing the amount of characters it contains.


string.lower(string)

Converts a string to lowercase.


string.upper(string)

Converts a string to uppercase.


string.rep(strToRepeat, intRepeatTimes)

Duplicates and concatenates a string indicated the number of times.


string.reverse(string)

Reverses a string.


string.sub(strOriginal, intStartIndex, intEndIndex)

Extract a substring from a string.

Standard Lua Functions

These are the standard Lua functions available on our devices. Unlike the rest of the libraries, they do not require a prefix.

Overview

FunctionShort DescriptionNote
assertspecific error trigger
collectgarbagemanual garbage collecting
errorcustom error message
gcinfocurrent memory use
getfenvcurrent environment table
getmetatablemetatable of an object
setmetatable
loadstringcompile a piece of code
nextkey value pair in a table
pcallprotected function calling
printprint a string
rawequalcompare two values
rawgetget a table value
rawsetset a table value
selectreturn an indexed value
selectreturn the argument count
setfenvset environment
tonumberconvert to number
tostringconvert to string
typereturn a data type
unpackunpack table
xpcallfunction with an error handler

assert(triggerCondition, strErrorMessage)

A method that triggers a custom error message when specific condition is met.


collectgarbage(strCommand)

Allows for manual control of (otherwise automatic) garbage collecting.


error(strErrorMessage)

Triggers an error with a custom message.


gcinfo()

Returns a value of Kb that are currently in dynamic memory use. Basically the same functionality as collectgarbage("count").


getfenv(table, intIndex)

Returns the current environment table.


getmetatable(object)

Returns the metatable for the object.


setmetatable()

text


loadstring(strCode)

Compiles a string of Lua code.


next(table, intIndex)

Returns next key / value pair in a table.


pcall(code)

Calls a function in protected mode. Especially useful, if we want the script to keep running despite the potential errors.


print(argument1, argument2, ...)

Prints its arguments to a string, primarily used for feedback.


rawequal(value1, value2)

Compares two values and determines, whether they are equal and returns true or false.


rawget(table, intIndex)

Gets the value of a table item without invoking metamethods.


rawset(table, intIndex, newValue)

Gets the value of a table item without invoking metamethods.


select(intIndex, value1, value2, ...)

Returns all the values starting with a specific index.

If I have 4 arguments with value, it would return 2 arguments if I use index of 3.


select("#", value1, value2, ...)

Returns the amount of arguments passed after the operator.

If I have 4 arguments with value, it would return 4.


setfenv(f, environment)

Sets the current environment to be used by f, which can be a function, userdata, thread or stack level. Level 1 is the current function. Level 0 is the global environment of the current thread. The "env" argument is a table, which effectively becomes the "root" for the environment.


tonumber(valueToBeConverted)

Converts the value provided to it into a number.

If this argument is a number or a convertible string, the tonumber() function returns the converted number.

If it is not a number or a convertible string, it will return nil.


tostring(value)

Converts a value, usually number, to string.


type(argument)

Returns the data type of the argument.


unpack(table)

Unpacks a table into individual values.


xpcall(funcToCall, funcErrorHandler)

Calls a function with a custom error handler.

If an error occurs in function it is caught and the error-handler is called. Then xpcall returns false, and whatever the error handler returned.